package com.juzipi.framework.security.handler;

import com.juzipi.common.constant.json.ResultCode;
import com.juzipi.common.tools.Result;
import com.juzipi.common.tools.ResultTool;
import com.juzipi.common.utils.StringUtils;
import com.juzipi.common.utils.json.JsonAuthentication;
import com.juzipi.framework.web.service.LoginUserService;
import com.juzipi.framework.web.service.TokenService;
import com.juzipi.inter.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出成功
 */

@Component
public class MyLogoutSuccessHandler extends JsonAuthentication implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private LoginUserService loginUserService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
        if (StringUtils.isNotNull(loginUser)){
            String uuid = loginUser.getUuid();
            //删除用户在redis中存的登录信息
            tokenService.delLoginUser(uuid);
            loginUserService.logout(loginUser.getUsername());
        }
        Result result = ResultTool.successCustomize(ResultCode.LOGOUT_SUCCESSFULLY);

        this.WriteJson(httpServletRequest,httpServletResponse,result);
    }
}
